import React from 'react';
import { PlusCircle, MessageSquare, ChevronLeft, Trash2 } from 'lucide-react';
import { useAIChat } from '@/contexts/aiChat';
import { type ConversationSummary } from '@/types/aiChat';

/**
 * 聊天侧边栏组件
 * 显示对话历史记录和新建对话按钮
 */
const ChatSidebar: React.FC = () => {
  const { 
    isSidebarOpen, 
    toggleSidebar, 
    createNewConversation, 
    selectConversation,
    deleteConversation,
    currentConversationId,
    getGroupedConversations 
  } = useAIChat();
  
  // 获取分组后的对话列表
  const groupedConversations = getGroupedConversations();
  
  if (!isSidebarOpen) {
    return (
      <button
        onClick={toggleSidebar}
        className="absolute left-0 top-1/2 -translate-y-1/2 bg-background border border-l-0 border-border rounded-r-md p-1 text-muted-foreground hover:text-foreground"
        aria-label="打开侧边栏"
      >
        <ChevronLeft className="w-4 h-4 rotate-180" />
      </button>
    );
  }
  
  return (
    <div className="w-64 h-full border-r border-border flex flex-col bg-background">
      {/* 侧边栏头部 */}
      <div className="p-3 border-b border-border flex items-center justify-between">
        <h3 className="font-medium text-sm">对话历史</h3>
        <button
          onClick={toggleSidebar}
          className="w-6 h-6 rounded-full hover:bg-accent flex items-center justify-center text-muted-foreground hover:text-foreground"
          aria-label="关闭侧边栏"
        >
          <ChevronLeft className="w-4 h-4" />
        </button>
      </div>
      
      {/* 新建对话按钮 */}
      <button
        onClick={createNewConversation}
        className="m-3 flex items-center justify-center gap-2 p-2 rounded-md bg-primary text-primary-foreground hover:bg-gray-700 dark:hover:bg-gray-600 transition-colors"
        aria-label="开始新对话"
      >
        <PlusCircle className="w-4 h-4" />
        <span className="text-sm font-medium">开启新对话</span>
      </button>
      
      {/* 对话列表 */}
      <div className="flex-1 overflow-y-auto">
        {Object.entries(groupedConversations).map(([group, conversations]) => (
          <div key={group} className="mb-2">
            <h4 className="px-3 py-1 text-xs font-medium text-muted-foreground bg-accent/30">
              {group}
            </h4>
            <ul>
              {conversations?.map((conversation: ConversationSummary) => (
                <ConversationItem
                  key={conversation.id}
                  conversation={conversation}
                  isActive={conversation.id === currentConversationId}
                  onSelect={() => selectConversation(conversation.id)}
                  onDelete={() => deleteConversation(conversation.id)}
                />
              ))}
            </ul>
          </div>
        ))}
        
        {Object.keys(groupedConversations).length === 0 && (
          <div className="p-3 text-center text-muted-foreground text-sm">
            暂无对话历史
          </div>
        )}
      </div>
    </div>
  );
};

// 对话项组件
interface ConversationItemProps {
  conversation: ConversationSummary;
  isActive: boolean;
  onSelect: () => void;
  onDelete: () => void;
}

const ConversationItem: React.FC<ConversationItemProps> = ({ 
  conversation, 
  isActive, 
  onSelect,
  onDelete
}) => {
  // 处理删除按钮点击，阻止事件冒泡以避免触发选择事件
  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    onDelete();
  };
  return (
    <li>
      <button
        onClick={onSelect}
        className={`w-full px-3 py-2 text-left flex items-start gap-2 hover:bg-accent/50 group ${
          isActive ? 'bg-accent' : ''
        }`}
        aria-current={isActive ? 'true' : 'false'}
      >
        <MessageSquare className="w-4 h-4 mt-0.5 flex-shrink-0 text-muted-foreground" />
        <div className="overflow-hidden flex-1">
          <div className="text-sm font-medium truncate">{conversation.title}</div>
          <div className="text-xs text-muted-foreground truncate">{conversation.preview}</div>
        </div>
        <button
          onClick={handleDelete}
          className="w-6 h-6 rounded-full flex items-center justify-center text-muted-foreground hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity"
          aria-label="删除对话"
          title="删除对话"
        >
          <Trash2 className="w-3.5 h-3.5" />
        </button>
      </button>
    </li>
  );
};

export default ChatSidebar;
